import re
from django.contrib.auth.backends import ModelBackend
from django.views import View
from itsdangerous import BadData

from apps.users.models import User
from meiduo_mall import settings


class UserMobileModelBackend(ModelBackend,View):
    def authenticate(self, request, username=None, password=None, **kwargs):
        #username 有可能是用户名也有可能是手机号
        #先判断是不是手机号
        try:
            if re.match(r"1[3-9]\d{9}",username):
                user = User.objects.get(mobile__exact=username)
            else:
                user = User.objects.get(username__exact=username)
        except User.DoesNotExist:
            return None
        if user.check_password(password):
            return user
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
def generic_verify_email_url(user_id):
    s = Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)
    data = {
        'user_id':user_id
    }
    token = s.dumps(data)
    return settings.EMAIL_VERIFY_URL + "?token=" + token.decode()
def check_verify_email_token(token):
    s = Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)
    try:
        result = s.loads(token)
    except BadData:
        return None
    return result.get('user_id')
